<template>
    <div class="container" style="background-color: #F5F9FF;height:880px ;width: 1648px;">
        <div class="bk" style="background-color: white; width: 1200px ;">
            <!-- <div class="btn-group">
                <el-button type="primary" @click="Add">新增</el-button>
                <el-button type="primary" @click="Update">批量操作</el-button>
                <el-button type="primary" @click="XQ">导入</el-button>
                <el-button type="primary">打印</el-button>
            </div> -->
            <div class="btn-group1">
                <!-- 查询所有状态 -->
                <el-button type="primary" @click="QB">全部</el-button>
                <!-- 查询待接单状态 -->
                <el-button type="primary" @click="show11(1)">待接单</el-button>
                <!-- 查询待提货状态 -->
                <el-button type="primary" @click="show11(2)">待提货</el-button>
                <!-- 查询待发车状态 -->
                <el-button type="primary" @click="show11(3)">待发车</el-button>
                <!--查询运输中状态-->
                <el-button type="primary" @click="show11(4)">运输中</el-button>
                <!--查询代签收状态-->
                <el-button type="primary" @click="show11(5)">待签收</el-button>
                <!--查询已完成状态-->
                <el-button type="primary" @click="show11(6)">已完成</el-button>
                <!--查询已取消状态-->
                <el-button type="primary" @click="show11(7)">已取消</el-button>
            </div>

            <div class="search-bar">
                <el-form ref="form" :inline="true" :model="searchForm" class="demo-form-inline">
                    <el-form-item label="始发地：">
                        <el-input v-model="sfd" placeholder="请输入始发地"></el-input>
                    </el-form-item>
                    <el-form-item label="目的地：">
                        <el-input v-model="mdd" placeholder="请输入目的地"></el-input>
                    </el-form-item>
                    <el-form-item label="运输方式：">
                        <el-select v-model="ysfs" placeholder="请选择" style="width: 120px">
                            <el-option v-for="item in ystableData" :key="item.value" :label="item.dict_label"
                                :value="item.dict_value" />
                        </el-select>
                    </el-form-item>

                </el-form>
            </div>
            <div class="search-bar1">
                <el-form ref="form" :inline="true" :model="searchForm" class="demo-form-inline">
                    <!-- <el-form-item label="下单日期：">
                        <el-date-picker v-model="searchForm.dateRange" type="daterange" start-placeholder="请选择日期"
                            end-placeholder="请选择日期" style="width: 280px"></el-date-picker>
                    </el-form-item> -->
                    <el-form-item label="搜索：">
                        <el-input v-model="wb_number" placeholder="请输入运单号搜索"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <div class="table-wrap">
                <el-table :data="tableData" stripe style="width: 1200px">
                    <el-table-column prop="wb_id" label="运单id" width="120" v-if="false"></el-table-column>
                    <el-table-column prop="wb_number" label="运单号" width="120">
                        <template #default="scope">
                            <el-button link type="primary" @click="XQ(scope.row.wb_id, scope.row.ord_id)">
                                {{ scope.row.wb_number }}
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="origin_place" label="始发地" width="120"></el-table-column>
                    <el-table-column prop="det_place" label="目的地" width="120"></el-table-column>
                    <el-table-column prop="wb_status" label="运单状态" width="120">
                        <template #default="scope">
                            <soan style="color: #00FF00;">{{ scope.row.wb_status }}</soan>
                        </template>
                    </el-table-column>
                    <el-table-column prop="tran_manager" label="运输方式" width="120"></el-table-column>
                    <el-table-column prop="cr_id" label="承运商" width="120"></el-table-column>
                    <el-table-column prop="dv_id" label="司机" width="120"></el-table-column>
                    <el-table-column prop="driver_phone" label="手机号码" width="120"></el-table-column>
                    <el-table-column prop="vc_id" label="车牌号" width="120"></el-table-column>
                    <el-table-column prop="vc_model" label="车型" width="120"></el-table-column>
                    <el-table-column prop="vc_length" label="车长" width="120"></el-table-column>
                    <el-table-column prop="bill_method" label="计费方式" width="120"></el-table-column>
                    <el-table-column prop="freight_costs" label="运费合计" width="120"></el-table-column>
                    <el-table-column prop="plan_time" label="计划发车时间" width="120"></el-table-column>
                    <el-table-column prop="reality_time" label="实际发车时间" width="120"></el-table-column>
                    <el-table-column prop="planget_time" label="计划到达时间" width="120"></el-table-column>
                    <el-table-column prop="realityget_time" label="实际到达时间" width="120"></el-table-column>
                    <!-- <el-table-column prop="to_time" label="接单时间" width="120"></el-table-column> -->
                    <el-table-column prop="order_time" label="下单时间" width="120"></el-table-column>
                    <el-table-column prop="create_by" label="创建人" width="120"></el-table-column>
                    <el-table-column prop="create_time" label="创建时间" width="120"></el-table-column>
                    <el-table-column prop="audit_status" label="审核状态" width="120">
                        <template #default="scope">
                            <span>{{ Status(scope.row.audit_status) }}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="payable_status" label="结算状态" width="120"></el-table-column> -->
                    <el-table-column label="操作" width="280px">
                        <template #default="scope">
                            <el-button type="text" size="small"
                                @click="Update(scope.row.wb_id, scope.row.ord_id)">编辑</el-button>
                            <el-button type="text" size="small"
                                @click="XQ(scope.row.wb_id, scope.row.ord_id)">详情</el-button>
                            <el-button type="text" size="small" @click="SH(scope.row)">审核</el-button>
                            <el-button type="text" size="small" @click="handleDelete(scope.row.wb_id)">取消调度</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination-wrap">
                    <el-pagination v-model:current-page="CurrentPage" v-model:page-size="PageSize"
                        :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="Countnum"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>

        <!-- 删除提示框 -->
        <!-- <el-dialog title="提示" :visible.sync="showDelete">
            <span>确认删除该客户吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showDelete = false">取消</el-button>
                <el-button type="primary" @click="deleteCustomer">确定</el-button>
            </span>
        </el-dialog> -->
    </div>
</template>

<script>
import router from '@/router';
import { onMounted, ref, reactive } from 'vue'
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Phone, Plus } from '@element-plus/icons-vue';
import { Upload } from 'element-plus';
import { useRouter, useRoute } from "vue-router";
import $http from '@/axios/base.js';

export default {
    setup() {
        let tableData = ref([]);   //运单数据
        const CurrentPage = ref(1);
        const PageSize = ref(10);
        let sfd = ref('');  //始发地
        let mdd = ref('');  //目的地
        let ysfs = ref('');  //运输方式
        let ystableData = ref([]);  //运输方式下拉框
        let wb_number = ref('');   //运单号
        let Countnum = ref('');   //数据条数

        onMounted(() => {
            show();
            show10();
            // count();
        })

        function show() {   //查询运单数据
            $http.get(`http://localhost:5261/api/Wb_meter/GetWb_meter/${CurrentPage.value},${PageSize.value}`).then((res) => {
                tableData.value = res;
                console.log(tableData.value);
                tableData.value.forEach(item => {
                    item.create_time=new Date(item.create_time).toISOString().slice(0, 10);
                    item.plan_time=new Date(item.plan_time).toISOString().slice(0, 10);
                    item.reality_time=new Date(item.reality_time).toISOString().slice(0, 10);
                    item.planget_time=new Date(item.planget_time).toISOString().slice(0, 10);
                    item.realityget_time=new Date(item.realityget_time).toISOString().slice(0, 10);
                    item.order_time=new Date(item.order_time).toISOString().slice(0, 10);
                });
                show2();
                show3();
                show4();
                show7();
                show8();
                show9();
                count();
            }).catch((err) => {
                if(err.Status == -1){
                    console.log("请求超时");
                }else{
                    console.log("错误:" + err);
                }
            })
        }

        function show2() {  //根据id查询司机司机名称
            tableData.value.forEach((item, index) => {
                $http.get(`http://localhost:5261/api/Order/GetDrivers_Ments_id/${item.dv_id}`).then((res2) => {
                    tableData.value[index].dv_id = res2[0].dv_name;
                    tableData.value[index].driver_phone = res2[0].dv_phone;
                })
            });
        }

        function show3() {   //根据id查询承运商
            tableData.value.forEach((item, index) => {
                $http.get(`http://localhost:5261/api/Carrier_ment/GetCarrier_Ments_Update?Cr_id=` + item.cr_id).then((res) => {
                    tableData.value[index].cr_id = res[0].cr_cp_name;
                })
            });
        }

        function show4() {   //根据id查询车牌号
            for (let index = 0; index < tableData.value.length; index++) {
                const item = tableData.value[index];
                $http.get(`http://localhost:5261/api/Vehicles/GetById/${item.vc_id}`).then((res2) => {
                    tableData.value[index].vc_id = res2.vc_phone;
                    tableData.value[index].vc_model = res2.vc_model;
                    tableData.value[index].vc_length = res2.vc_length;
                    show5(res2.vc_model, index);
                    show6(res2.vc_length, index);
                    console.log(res2);
                })
            }
        }

        function show5(model, index) {   //查询车型
            $http.get(`http://localhost:5261/api/Sys_Dict_data/GetSys_Dict_datacode?Dict_code=` + model).then((res) => {
                tableData.value[index].vc_model = res;
            })
        }

        function show6(length, index) {   //查询车长
            $http.get(`http://localhost:5261/api/Sys_Dict_data/GetSys_Dict_datacode?Dict_code=` + length).then((res) => {
                tableData.value[index].vc_length = res;
            })
        }

        function show7() {  //查询运单状态
            tableData.value.forEach((item, index) => {
                switch (tableData.value[index].wb_status) {
                    case 1:
                        tableData.value[index].wb_status = '待接单';
                        break;
                    case 2:
                        tableData.value[index].wb_status = '待提货';
                        break;
                    case 3:
                        tableData.value[index].wb_status = '待发车';
                        break;
                    case 4:
                        tableData.value[index].wb_status = '运输中';
                        break;
                    case 5:
                        tableData.value[index].wb_status = '待签收';
                        break;
                    case 6:
                        tableData.value[index].wb_status = '已完成';
                        break;
                    case 7:
                        tableData.value[index].wb_status = '已取消';
                        break;
                    case 8:
                        tableData.value[index].wb_status = '已拒绝';
                        break;
                    default:
                        tableData.value[index].wb_status = '未知状态';
                        break;
                }
            })
        }

        function show8() {   //查询运输方式
            tableData.value.forEach((item, index) => {
                switch (tableData.value[index].tran_manager) {
                    case 0:
                        tableData.value[index].tran_manager = '汽车运输';
                        break;
                    case 1:
                        tableData.value[index].tran_manager = '海运';
                        break;
                    case 2:
                        tableData.value[index].tran_manager = '空运';
                        break;
                    case 3:
                        tableData.value[index].tran_manager = '铁路';
                        break;
                }
            });
        }

        function show9(bill_method, index) {   //计费方式
            // tableData.value.forEach((item, index) => {
            //     switch (tableData.value[index].bill_method) {
            //         case 0:
            //             tableData.value[index].bill_method = '按车计费';
            //             break;
            //         case 1:
            //             tableData.value[index].bill_method = '按重量计费';
            //             break;
            //         case 2:
            //             tableData.value[index].bill_method = '按体积计费';
            //             break;
            //         default:
            //             tableData.value[index].wb_status = '未知状态';
            //             break;
            //     }
            // });
            tableData.value.forEach((item, index) => {
                $http.get(`http://localhost:5261/api/Sys_Dict_data/GetSys_Dict_datacode?Dict_code=` + item.bill_method).then((res) => {
                    tableData.value[index].bill_method = res;
                })
            })
        }

        function show10() {  //查询运输方式
            $http.get("http://localhost:5261/api/Sys_Dict_data/GetSys_Dict_Datas?type=Tran_manager").then((res) => {
                ystableData.value = res;
            }).catch((err) => {
                console.log("错误:" + err);
            })
        }

        const searchForm = reactive({
            level: "1",
            dateRange: "",
            keyword: "",
        });


        let currentRow = ref(null);
        let showDelete = ref(false);

        function handleSearch() {   //搜索
            $http.get(`http://localhost:5261/api/Wb_meter/GetWb_Meters?Origin_place=` + sfd.value + `&Det_place=` + mdd.value + `&tran_manager=` + ysfs.value + `&Wb_number=` + wb_number.value + `&currentPage=` + CurrentPage.value + `&PageSize=` + PageSize.value).then((res) => {
                tableData.value = res;
                show2();
                show3();
                show4();
                show7();
                show8();
                show9();
                count();
            }).catch((err) => {
                console.log("错误:" + err);
            })
        }

        function handleReset() {  //重置
            sfd.value = '';  //始发地
            mdd.value = '';  //目的地
            ysfs.value = '';  //运输方式
            wb_number.value = '';   //运单号
            show();
        }

        function handleAddress(row) {
            console.log("查看地址", row);
        }

        function handleEdit(row) {
            console.log("编辑客户", row);
        }

        function handleDelete(id) {  //取消调度（删除）
            ElMessageBox.confirm(
                '确认是否取消调度?', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning',
                draggable: true,
                overflow: true,
                lockScroll: false //防止抖动
            }).then(() => {
                $http.delete(`http://localhost:5261/api/Wb_meter/Delete/${id}`).then((res) => {
                    if (res) {
                        ElMessage.success("删除成功!");
                        show();
                    }
                }).catch((err) => {
                    ElMessage.warning("删除失败!");
                })
            }).catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消',
                })
            })

        }

        // function deleteCustomer() {
        //     const index = tableData.value.findIndex((item) => item === currentRow.value);
        //     if (index >= 0) {
        //         tableData.value.splice(index, 1); // 从数据列表中删除指定行
        //     }
        //     deleteDialogVisible.value = false; // 关闭删除确认对话框
        // }

        function Add() {
            router.push('/YDAdd')
        }

        function Update(wb_id, ord_id) {   //跳转到编辑页面
            router.push({ path: '/YDUpdate', query: { wb_id, ord_id } })
        }

        function XQ(wb_id, ord_id) {
            router.push({ path: '/YDXQ', query: { wb_id, ord_id } })
        }

        function handleSizeChange(val) {   //分页条数变化
            PageSize.value = val;
            //console.log(PageSize.value);
            show();
        }

        function handleCurrentChange(val) {  //分页页数变化
            CurrentPage.value = val;
            show();
        }

        function count() {   //总数
            $http.get(`http://localhost:5261/api/Wb_meter/Count?Origin_place=` + sfd.value + `&Det_place=` + mdd.value + `&tran_manager=` + ysfs.value + `&Wb_number=` + wb_number.value).then((res) => {
                Countnum.value = res;
            })
        }

        function QB() {   //全部
            show();
        }

        function count2(value) {   //运单状态查询的数量
            $http.get(`http://localhost:5261/api/Wb_meter/Count_status/${value}`).then((res) => {
                Countnum.value = res;
            })
        }

        function show11(value) {   //根据运单状态查询数据
            $http.get(`http://localhost:5261/api/Wb_meter/GetWb_Meters_status/${value},${CurrentPage.value},${PageSize.value}`).then((res) => {
                tableData.value = res;
                console.log(tableData.value);
                show2();
                show3();
                show4();
                show7();
                show8();
                show9();
                count2(value);
            }).catch((err) => {
                console.log("错误:" + err);
            })
        }

        function Status(value) {
            switch (value) {
                case 0:
                    return "未审核";
                case 1:
                    return "已审核";
            }
        }

        let form = reactive({   //提货单数据
            // Billol_Id: 0,        // 提货单Id
            Wb_Id: 0,            // 运单Id
            Customer: '',        // 客户
            Bill_Status: 0,      // 提货状态
            Bill_Id: '',         // 提货单号
            Wb_number: '',       // 运单号
            Order_Id: '',        // 订单号
            Origin_place: '',    // 始发地
            Det_place: '',       // 目的地
            Pickup_address: '',  // 提货地址
            Delivery_address: '',// 收货地址
            Driver_name: '',     // 提货司机
            Car_number: '',      // 车牌号
            Driver_phone: '',    // 手机号
            Bill_nums: 0,        // 提货数量
            Bill_volume: 0.0,    // 提货体积
            Bill_weight: 0.0,    // 提货重量
            Bill_cost: 0.0,      // 提货运费合计
            Pickup_time: new Date(), // 提货开始时间
            Pickup_endtime: new Date(), // 提货结束时间
            Plan_time: '', // 计划发车时间
            Reality_time: '', // 实际发车时间
            PlanGet_time: '', // 计划到达时间
            RealityGet_time: '', // 实际到达时间
            Del_flag: 0,         // 删除标志
            Ord_id: 0,           // 订单ID
            Create_time: new Date(), // 创建时间
            Create_by: sessionStorage.getItem("empname")        // 创建人
        });

        async function SH(bill_bol) {
            form.Wb_Id = bill_bol.wb_id;
            await show12(bill_bol.ord_id);
            form.Bill_Status = 0;
            await BH();
            form.Wb_number = bill_bol.wb_number;
            form.Origin_place = bill_bol.origin_place;
            form.Det_place = bill_bol.det_place;
            form.Driver_name = bill_bol.dv_id;
            form.Car_number = bill_bol.vc_id;
            form.Driver_phone = bill_bol.driver_phone;
            form.Bill_cost = bill_bol.freight_count;
            form.Plan_time = bill_bol.plan_time;
            form.Reality_time = bill_bol.reality_time;
            form.PlanGet_time = bill_bol.planget_time;
            form.RealityGet_time = bill_bol.realityget_time;
            form.Ord_id = bill_bol.ord_id;
            console.log(form);
            $http.post(`http://localhost:5261/api/Wb_meter/Add_Bill_ol`, form).then((res) => {
                if (res) {
                    ElMessage.success("审核成功!");
                    show();
                } else {
                    ElMessage.warning("审核失败!");
                    show();
                }
            })
            show13(bill_bol.wb_id);
        }

        async function show12(value) {   //根据订单id查询订单
            await $http.get(`http://localhost:5261/api/Wb_meter/GetOrders/${value}`).then((res) => {
                form.Customer = res[0].client_name;   //客户名称
                form.Order_Id = res[0].ord_number;   //订单号
                form.Pickup_address = res[0].shipments_addres;   //提货地址
                form.Delivery_address = res[0].receiving_addres;   //收货地址
                form.Bill_nums = res[0].count;   //提货数量
                form.Bill_volume = res[0].totalvolume;   //提货体积
                form.Bill_weight = res[0].weight;   //提货重量
            }).catch((err) => {
                console.log("错误:" + err);
            })
        }

        async function BH() {   //生成提货单号
            await $http.get(`http://localhost:5261/api/BH/BHGZ?prefix=TH`).then((res) => {
                form.Bill_Id = res;
                BH2();
            }).catch((err) => {
                console.log("错误:" + err);
            })
        }

        function BH2() {   //修改编号最大值
            $http.get(`http://localhost:5261/api/BH/GetBH?prefix=TH`).then((res) => {
                console.log(res);
            }).catch((err) => {
                console.log("错误:" + err);
            })
        }

        function show13(value) {
            $http.put(`http://localhost:5261/api/Wb_meter/Update_status/${value}`).then((res) => {
                if (res) {

                } else {
                    ElMessage.warning("审核状态未修改")
                }
            }).catch((err) => {
                console.log("错误:" + err);
            })
        }

        return {
            tableData,
            searchForm,
            CurrentPage,
            PageSize,
            handleSearch,
            handleReset,
            // handlePageChange,
            handleAddress,
            handleEdit,
            handleDelete,
            //deleteCustomer,
            currentRow,
            Add,
            Update,
            XQ,
            ystableData,
            mdd,
            sfd,
            ysfs,
            wb_number,
            handleSizeChange,
            handleCurrentChange,
            Countnum,
            count,
            QB,
            count2,
            show11,
            Status,
            form,
            SH,
            show12
        };
    },
};
</script>

<style>
.container {
    padding: 20px;
}

.btn-group {
    margin-bottom: 20px;
    margin-left: -800px;
}

.btn-group1 {
    margin-bottom: 20px;
    margin-left: -515px;
}

.search-bar {
    margin-bottom: 20px;
    margin-left: -330px;
}

.search-bar1 {
    margin-bottom: 20px;
    margin-left: -300px;
}

.pagination-wrap {
    margin-top: 20px;
    text-align: right;
}
</style>